package server;


import java.io.File;
import java.sql.SQLException;
import constans.CapsuleConstans;
import database.DatabaseOperationsCapsules;
import database.DatabaseOperationsCapsulesTemporary;


public  class Recovery {


	private DatabaseOperationsCapsulesTemporary dbOpCapsulesTemporary;
	private DatabaseOperationsCapsules dbOpCapsules;
	private File folderCapsuleTemporary;


	public Recovery(DatabaseOperationsCapsulesTemporary dbOpCapsulesTemporary , DatabaseOperationsCapsules dbOpCapsules,
			File folderCapsuleTemporary)
	throws SQLException{
		this.dbOpCapsulesTemporary = dbOpCapsulesTemporary;
		this.dbOpCapsules = dbOpCapsules;
		this.folderCapsuleTemporary = folderCapsuleTemporary;
	}


	public boolean getRecoveryCapsule(String nameCapsule, String email, int  id)
	throws SQLException{	

		if(dbOpCapsules.existsCapsule(nameCapsule)){
			if(! dbOpCapsules.isCapsuleRestore(nameCapsule)){

				if(!dbOpCapsulesTemporary.existsCapsuleTemporay(nameCapsule, email,id)){
					dbOpCapsulesTemporary.insertCapsuleTemporay(nameCapsule, email,id);
					return true;
				}
				else{
					if(dbOpCapsulesTemporary.isCompleteCapsuleTemporay(nameCapsule, email,id)){
                        return false;
                    }
					else{
						return true;
                    }
				}

			}else{
				
				if(dbOpCapsulesTemporary.existsCapsuleTemporay(nameCapsule, email,id)){
					dbOpCapsulesTemporary.deleteCapsuleTemporary(nameCapsule, email,id);
					deleteCapsuleTemporaryFile(nameCapsule, email,id);
				}
					
				return false;
			}
			
		} else{
			return false;
		}

	}

	
    public long getCapsuleLength(String nameCapsule)
	throws SQLException{
		return dbOpCapsules.getLengthCapsule(nameCapsule);
	}
	
	
	public void close()
	throws SQLException{
		if(dbOpCapsulesTemporary!=null){
			dbOpCapsulesTemporary.close();
			dbOpCapsulesTemporary = null;
		}
		if(dbOpCapsules!=null){
			dbOpCapsules.close();
			dbOpCapsules = null;
		}
	}
	
	
	private void deleteCapsuleTemporaryFile(String nameCapsule, String email, int id) {
		
		File file = new File (folderCapsuleTemporary,nameCapsule+email+id+CapsuleConstans.CAPSULE_TEMPORARY_EXTENSION);
		
		file.delete();
		
		file = null;		
	}


}
